package com.seaboxdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.seaboxdata.dao.*;
import com.seaboxdata.entity.*;
import com.seaboxdata.service.*;
import java.text.SimpleDateFormat;
import java.util.stream.Collectors;
import org.apache.commons.lang.time.DateUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;

/**
 * @author
 * @create 2021-01-04 11:39
 **/
@Service
public class IndicatorsServiceImpl implements IndicatorsService {

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private EpidemicDataInfoDao epidemicDataInfoDao;

    @Autowired
    private TableConfigDao tableConfigDao;

    @Autowired
    private ServiceInfoDao serviceInfoDao;

    @Autowired
    private ShareTableInfoService shareTableInfoService;

    @Autowired
    private ShareWayInfoDao shareWayInfoDao;

    @Autowired
    private DataShareInfoService dataShareInfoService;

    @Autowired
    private DataRealInfoService dataRealInfoService;

    @Autowired
    private DataCountInfoService dataCountInfoService;

    @Autowired
    private GovernanceInfoDao governanceInfoDao;

    @Autowired
    private DataCountInfoDao dataCountInfoDao;

    @Override
    public Map<String, Object> getSharedInfo() {
        Map<String, Object> map = new HashMap<>();
        //共享系统数量
        map.put("sharedSystemCount", shareTableInfoService.getShareSystemCount());
        //共享表数量
        map.put("shareTableCount", shareTableInfoService.getShareTableCount());
        return map;
    }

    @Override
    public Map<String, Object> getDataSourceInfo() {
        List<JSONObject> jsonList = tableConfigDao.getDataSourceInfo();
        Map<String, Object> map = new HashMap<>();
        for(JSONObject json : jsonList){
            String data_source = json.getString("data_source");
            String value = json.getString("count");
            //0-省市，1-新区，2-社会
            if("0".equals(data_source)){
                map.put("cityCount",value);
            }else if("1".equals(data_source)){
                map.put("areaCount",value);
            }else if("2".equals(data_source)){
                map.put("policyCount",value);
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> getDTypeInfo() {
        List<JSONObject> jsonList = tableConfigDao.getDTypeInfo();
        Map<String, Object> map = new HashMap<>();
        for(JSONObject json : jsonList){
            String dtype = json.getString("dtype");
            String value = json.getString("count");
            //0-其他，1-人口，2-房屋，3-法人，4-空间地理,5-电子证照，6-公共信用
            if("0".equals(dtype)){
                map.put("otherCount",value);
            }else if("1".equals(dtype)){
                map.put("peopleCount",value);
            }else if("2".equals(dtype)){
                map.put("houseCount",value);
            }else if("3".equals(dtype)){
                map.put("legalCount",value);
            }else if("4".equals(dtype)){
                map.put("spaceCount", value);
            } else if ("5".equals(dtype)) {
                map.put("pictureCount", value);
            } else if ("6".equals(dtype)) {
                map.put("creditCount", value);
            }
        }
        return map;
    }

    public static Date getYesterday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        return DateUtils.addDays(date, -1);
    }

    @Override
    public Map<String, Object> getShareWayInfo() {
        QueryWrapper<ShareWayInfo> qw = new QueryWrapper<>();
//        qw.eq("data_dt", new Date());
        qw.orderByDesc("data_dt");
        ShareWayInfo shareWayInfo = shareWayInfoDao.selectOne(qw);
        return BeanUtils.beanToMap(shareWayInfo);
    }

    @Override
    public List<ServiceInfo> getServiceInfo() {
        QueryWrapper<ServiceInfo> qw = new QueryWrapper<>();
        qw.orderByDesc("data_dt");
        List<ServiceInfo> serviceInfos = serviceInfoDao.selectList(qw);
        if (CollectionUtils.isNotEmpty(serviceInfos)) {
            serviceInfos = serviceInfos.stream().limit(7).collect(Collectors.toList());
        }
        return serviceInfos;
    }

    @Override
    public List<CirclesDepartment> getProvideCirclesInfo() {
        List<CirclesDepartment> circlesDepartmentList = departmentDao.getProvideCirclesInfo();
        return circlesDepartmentList;
    }

    @Override
    public  List<CirclesDepartment> getDepartmentDbInfo() {
        List<CirclesDepartment> list = departmentDao.getDepartmentDbInfo();
        return list;
    }

    @Override
    public  List<CirclesDepartment> getShareDbInfo() {
        List<CirclesDepartment> list = departmentDao.getShareDbInfo();
        return list;
    }

    @Override
    public  List<DataShareInfo> getDataShareDbInfo() {
        List<DataShareInfo> list = dataShareInfoService.getDataShareDbInfo();
        return list;
    }

    @Override
    public  Long getStaRealInfo() {
        Long total = dataRealInfoService.getStaRealInfo();
        return total;
    }

    @Override
    public  List<DataRealInfo> getFreRealInfo() {
        List<DataRealInfo> list = tableConfigDao.getFreRealInfo();
        return list;
    }

    @Override
    public  Integer getCountByTable(String tableName) throws Exception{
        return departmentDao.getCountByTable(tableName);
    }

    @Override
    public  String getSpaceSizeByTable(String tableName) throws Exception{
        return dataShareInfoService.getSpaceSizeByTable(tableName);
    }

    @Override
    public  int delCirclesDepartmentInfo(String type) {
        QueryWrapper<CirclesDepartment> qw = new QueryWrapper<>();
        LocalDate today = LocalDate.now();
        qw.eq("count_type", type);
        qw.eq("create_date", today);
        return departmentDao.delete(qw);
    }

    @Override
    public  Boolean insertDataRealInfo(List<DataRealInfo> dataRealInfo) {
        dataRealInfoService.saveBatch(dataRealInfo);
        return true;
    }

    @Override
    public  Boolean insertCirclesDepartmentInfo(CirclesDepartment circlesDepartment) {
        departmentDao.insert(circlesDepartment);
        return true;
    }

    @Override
    public  Boolean insertDataShareInfo(List<DataShareInfo> shareInfoList) {
        dataShareInfoService.saveBatch(shareInfoList);
        return true;
    }


    @Override
    public  Integer getPeopleNumber() {
        return epidemicDataInfoDao.getPeopleNumber();
    }


    @Override
    public  Integer getHstestNumber(Date date) {
        return epidemicDataInfoDao.getHstestNumber(date);
    }


    @Override
    public  Integer getYmjzNumber() {
        return epidemicDataInfoDao.getYmjzNumber();
    }


    @Override
    public Boolean insertEpidemicDataInfo(EpidemicDataInfo epidemicDataInfo) {
        epidemicDataInfoDao.insert(epidemicDataInfo);
        return true;
    }

    @Override
    public List<CirclesDepartment> getUseCirclesInfo() {
        List<CirclesDepartment> circlesDepartmentList = departmentDao.getUseCirclesInfo();
        return circlesDepartmentList;
    }

    @Override
    public List<EpidemicDataInfo> getEpidemicDataInfo() {
        QueryWrapper<EpidemicDataInfo> qw = new QueryWrapper<>();
        qw.gt("create_date", getYesterday());
        qw.orderByDesc("create_date");
        List<EpidemicDataInfo> retList = null;
        List<EpidemicDataInfo> list = epidemicDataInfoDao.selectList(qw);
        if (CollectionUtils.isNotEmpty(list)) {
            retList = list.stream().limit(1).collect(Collectors.toList());
        }
        return retList;
    }

    /**
     * 接入方式对比
     *
     * @return
     */
    @Override
    public List<DataItemType> getDataCompCountInfo() {
        List<DataCountInfo> infos = dataCountInfoService.getAccessWayData();
        Map<String, List<DataCountInfo>> collects = infos.stream()
                .collect(Collectors.groupingBy(DataCountInfo::getDataDt));
        DataItemType dataItemType = null;
        List<DataItemType> DataItemTypes = Lists.newArrayList();
        for (String key : collects.keySet()) {
            List<DataCountInfo> datas = collects.get(key);
            dataItemType = new DataItemType();
            for (DataCountInfo dc : datas) {
                //接入方式 0-库表，1-接口，2-填报，3-文件
                if ("0".equals(dc.getDataItemType())) {
                    dataItemType.setDbDataItemType("0");
                    dataItemType.setDbDataCount(dc.getDataCount() == null ? "0" : dc.getDataCount());
                    dataItemType.setFileDataCount(
                            String.valueOf(dc.getFileNum()) == null ? "0" : String.valueOf(dc.getFileNum()));
                    dataItemType.setDataDt(dc.getDataDt());
                } else if ("1".equals(dc.getDataItemType())) {
                    dataItemType.setApiDataItemType("1");
                    dataItemType.setApiDataCount(dc.getDataCount() == null ? "0" : dc.getDataCount());
                } else if ("2".equals(dc.getDataItemType())) {
                    dataItemType.setHandDataItemType("2");
                    dataItemType.setHandDataCount(dc.getDataCount() == null ? "0" : dc.getDataCount());
                }
            }
            DataItemTypes.add(dataItemType);
        }

        DataItemTypes = DataItemTypes.stream().sorted(Comparator.comparing(DataItemType::getDataDt).reversed())
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(DataItemTypes)) {
            DataItemTypes = DataItemTypes.stream().limit(7).sorted(Comparator.comparing(DataItemType::getDataDt))
                    .collect(Collectors.toList());
//            DataItemTypes = DataItemTypes.stream().sorted(Comparator.comparing(DataItemType::getDataDt)).collect(Collectors.toList());
        }

        return DataItemTypes;
    }

    /**
     * 获取 type=hot_data 热门数据，当天数据；
     *
     * @param type
     * @return
     */
    @Override
    public List<DataCountInfo> getDataCountInfo(String type) {
        List<DataCountInfo> list = dataCountInfoService.getHotData();
        return list;
    }


    @Override
    public List<DataCountInfo> getAccessWayInfo() {
        List<DataCountInfo> list = dataCountInfoService.getAccessWayInfo();
        return list;
    }

    @Override
    public  List<DataCountInfo> getHotDataInfo() {
        List<DataCountInfo> list = dataCountInfoService.getHotDataInfo();
        return list;
    }

    @Override
    public  Boolean insertDataCountInfo(List<DataCountInfo> accessWayInfos) {
        dataCountInfoService.saveBatch(accessWayInfos);
        return true;
    }

    @Override
    public  Boolean delDataCountInfo(String type) {
        QueryWrapper<DataCountInfo> qw = new QueryWrapper<>();
        LocalDate today = LocalDate.now();
        qw.eq("data_dt", today.toString());
        qw.eq("data_type", type);
        return dataCountInfoService.remove(qw);
    }

    @Override
    public Map<String, Object> getGovernanceInfo() {
        QueryWrapper<GovernanceInfo> qw = new QueryWrapper<>();
//        qw.eq("data_dt", new Date());
        qw.orderByDesc("data_dt");
        GovernanceInfo governanceInfo = governanceInfoDao.selectOne(qw);
        return BeanUtils.beanToMap(governanceInfo);
    }

    @Override
    public List<CirclesDepartment> getSysGovDataInfo() {
        List<CirclesDepartment> list = departmentDao.getSysGovDataInfo(getYesterday());
        if (CollectionUtils.isNotEmpty(list)) {
            list = list.stream().limit(3).collect(Collectors.toList());
        }
        return list;
    }

    /**
     * 查询资源数量排名-接入数量 （0-其他，1-接口）
     *
     * @return
     */
    @Override
    public List<CirclesDepartment> getResDataRankInfo() {
        return departmentDao.getResDataRankInfo();
    }

    /**
     * 查询数据资源情况-基础/主题/专题
     *
     * @return
     */
    @Override
    public List<CirclesDepartment> getResDbDataInfo() {
        return departmentDao.getResDbDataInfo();
    }


    /**
     * 越境司机预警数据
     *
     * @return
     */
    @Override
    public List<EpidemicDataInfo> getCrossDriverInfo() {
        String dt = LocalDate.now().minusDays(14).toString();
        List<EpidemicDataInfo> crossDriverInfo = epidemicDataInfoDao.getCrossDriverInfo(dt);
        if (CollectionUtils.isNotEmpty(crossDriverInfo)) {
            crossDriverInfo = crossDriverInfo.stream().limit(7).sorted(Comparator.comparing(EpidemicDataInfo::getNote))
                    .collect(Collectors.toList());
        }
        return crossDriverInfo;
    }

    @Override
    public List<DataCountInfo> getMppDataInfo() {
        return dataCountInfoDao.getMppDataInfo();
    }


}
